package com.common;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dao.sys.SysManageMapper;

/**
 * @author tfj 2014-8-1
 */
public class CommonInterceptor extends HandlerInterceptorAdapter {
	static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);
	@Autowired
	private SysManageMapper sysManageMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String requestUri = request.getRequestURI();
		// String contextPath = request.getContextPath();
		logger.info("url:{}", requestUri);
		// System.out.println("url:" + requestUri);
		if (requestUri.contains("sys/loginin") || requestUri.contains("/logincas")
				|| requestUri.contains("/loginMobile") || requestUri.contains("sys/logout")) {
			return true;
		}
		String username = (String) request.getSession().getAttribute("display_user");
		// System.out.println("username" + username);
		logger.info("username:{}", username);
		if (username == null || username.equals("")) {
			request.getRequestDispatcher("/index.jsp").forward(request, response);
			// response.sendRedirect(contextPath);
			return false;
		} else {
			return true;
		}
		// return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null) { //
			String userid = (String) request.getSession().getAttribute("display_userid");
			String url = request.getServletPath();
			if (url.length() > 0) {
				url = url.substring(1, url.length());
			}
			List<String> listP = sysManageMapper.GetPermission(userid, url);
			String pString = "";
			for (String s : listP) {
				pString += s + ",";
			}
			// System.out.println("permission:" + pString);
			logger.info("permission:{}", pString);
			request.getSession().setAttribute("display_permissions", pString);
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}